package com.decade.qiyeshapan.controller;

import cn.hutool.json.JSONObject;
import com.decade.qiyeshapan.model.ApiResponse;
import com.decade.qiyeshapan.entity.User;
import com.decade.qiyeshapan.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;


import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/users")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/add")
    public ApiResponse<String> addUser(@RequestBody User user) {
        try {
            userService.saveUser(user);
            return ApiResponse.success("User added successfully");
        } catch (IllegalArgumentException e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    @PostMapping("/get")
    public ApiResponse<User> getUser(@RequestBody Map<String, String> request) {
        String gameId = request.get("gameId");
        String username = request.get("username");
        User user = userService.getUser(gameId, username);
        return ApiResponse.success(user);
    }

    @PostMapping("/delete")
    public ApiResponse<String> deleteUser(@RequestBody Map<String, String> request) {
        String gameId = request.get("gameId");
        String username = request.get("username");
        userService.deleteUser(gameId, username);
        return ApiResponse.success("User deleted successfully");
    }

    @PostMapping("/all")
    public ApiResponse<Map<String, User>> getAllUsers(@RequestBody Map<String, String> request) {
        String gameId = request.get("gameId");
        Map<String, User> users = userService.getAllUsers(gameId);
        return ApiResponse.success(users);
    }

    @PostMapping("/updateProgress")
    public ApiResponse<String> updateProgress(@RequestBody Map<String, Object> request) {
        try {
            String gameId = (String) request.get("gameId");
            String username = (String) request.get("username");
            int progress = (Integer) request.get("progress");
            
            userService.updateProgress(gameId, username, progress);
            return ApiResponse.success("Progress updated");
        } catch (IllegalArgumentException e) {
            return ApiResponse.error(e.getMessage());
        } catch (ClassCastException e) {
            return ApiResponse.error("Invalid parameter type");
        }
    }

    @PostMapping("/updateSocketId")
    public ApiResponse<String> updateSocketId(@RequestBody Map<String, Object> request) {
        try {
            String gameId = (String) request.get("gameId");
            String username = (String) request.get("username");
            String socketId = (String) request.get("socketId");
            
            userService.updateSocketId(gameId, username, socketId);
            return ApiResponse.success("SocketId updated");
        } catch (IllegalArgumentException e) {
            return ApiResponse.error(e.getMessage());
        } catch (ClassCastException e) {
            return ApiResponse.error("Invalid parameter type");
        }
    }

    @PostMapping("/toggleReady")
    public ApiResponse<String> toggleReady(@RequestBody Map<String, String> request) {
        try {
            String gameId = request.get("gameId");
            String username = request.get("username");
            boolean isReady = Boolean.parseBoolean(request.get("isReady"));
            
            userService.toggleReady(gameId, username, isReady);
            return ApiResponse.success("准备状态更新成功");
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    @GetMapping("/{gameId}/players")
    public ResponseEntity<?> getPlayers(@PathVariable String gameId) {
        try {
            Map<String, User> users = userService.getAllUsers(gameId);
            JSONObject roomInfo = userService.getGameInfo(gameId);
            
            List<Map<String, Object>> playerList = users.values().stream()
                .map(u -> {
                    Map<String, Object> map = new java.util.HashMap<>();
                    map.put("username", u.getUsername());
                    map.put("isReady", u.isReady());
                    return map;
                })
                .collect(Collectors.toList());
            
            return ResponseEntity.ok(Map.of(
                "code", 200,
                "data", playerList,
                "totalPlayers", users.size(),
                "maxPlayers", 8
            ));
        } catch (Exception e) {
            return ResponseEntity.status(500).body(Map.of(
                "code", 500,
                "msg", "获取玩家列表失败: " + e.getMessage()
            ));
        }
    }

    @PostMapping("/updateTaskProgress")
    public ApiResponse<String> updateTaskProgress(@RequestBody Map<String, Object> request) {
        try {
            String gameId = (String) request.get("gameId");
            String username = (String) request.get("username");
            int progress = (Integer) request.get("progress");
            
            userService.updateTaskProgress(gameId, username, progress);
            return ApiResponse.success("任务进度更新成功");
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }
} 